//
//  LGShopViewController.m
//  LuxuryGoods
//
//  Created by 纳里健康 on 2018/5/25.
//  Copyright © 2018年 Future. All rights reserved.
//

#import "LGShopViewController.h"
#import "LGShopTableViewCell.h"
#import "LGShopModel.h"
#import "LGChooseAllTableViewCell.h"

#import "LGHomeSearcjViewController.h"
#import "UserInfoModel.h"



@interface LGShopViewController ()<UITableViewDelegate,UITableViewDataSource,AllChooseCelldelegate>
{
    UITableView *_tableView;
    
    NSMutableArray *_requestArray;
    
    LGShopModel *_shopModel; //虚拟的一个Model
    
    CGFloat _totalPrice; //合计价格
    
    BOOL _canDelete; //判断是删除或者结算
    
    UIButton *_editBtn;
    
    UIButton *_deleteBtn;
    
    NSMutableArray *_deleteArray;//删除数组
    
    NSMutableArray *_accountDataArray;//控制结算的数组
    
    NSMutableArray *_deleteDataArray;//删除的数据源数组
    
    CGFloat _productAllPrice;//总价
}

@end

@implementation LGShopViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"购物车";
    
    _totalPrice = 0;
    _deleteArray = [[NSMutableArray alloc] init];
    _accountDataArray = [[NSMutableArray alloc] init];
    _deleteDataArray = [[NSMutableArray alloc] init];
    
    _canDelete = NO;
    
    [self requestData];
    
    [self makeNavBar];
    
    [self maketableView];
    
}

- (void)requestData
{
    [[MainApi sharedInstance] postPath:@"Cart/getList" params:@{@"token":UserInfo.userToken} resultBlock:^(NSDictionary *responseObject, NSError *error) {
        NSInteger code = [responseObject[@"code"] integerValue];
    
        if(code == 1)
        {
            NSArray *dataArray = responseObject[@"data"];
            
            for (NSDictionary *dict in dataArray) {
                LGShopModel *model = [LGShopModel yy_modelWithJSON:dict];
                [self->_requestArray addObject:model];
                [self->_accountDataArray addObject:model];
                [self->_deleteDataArray addObject:model];
                
            }
        }
        
    }];

    
    
//    _shopModel = [[LGShopModel alloc] init];
//    _shopModel.goods_img = @"1";
//    _shopModel.goods_title = @"百达翡丽超级复杂功能计时自动机械机芯日期月相 6102P—001";
//    _shopModel.price = 12.80;
//    _shopModel.chooseOrNot = NO;
//
//    LGShopModel *model = [[LGShopModel alloc] init];
//    model.goods_img = @"2";
//    model.goods_title = @"百达翡丽超级复杂功能计时自动机械机芯日期月相 6102P—001";
//    model.price = 15.80;
//    model.chooseOrNot = NO;
//
//    LGShopModel *model2 = [[LGShopModel alloc] init];
//    model2.goods_img = @"3";
//    model2.goods_title = @"百达翡丽超级复杂功能计时自动机械机芯日期月相 6102P—001";
//    model2.price = 15.80;
//    model2.chooseOrNot = NO;
//
//    _requestArray = @[_shopModel,model,model2];
//    _accountDataArray = [NSMutableArray arrayWithObjects:_shopModel,model,model2, nil];
//    _deleteDataArray = [NSMutableArray arrayWithObjects:_shopModel,model,model2, nil];
    _productAllPrice = 0;
    for (LGShopModel *model in _requestArray) {
        _productAllPrice += model.price;
    }

}

- (void)makeNavBar
{
    _editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _editBtn.frame = CGRectMake(0, 0, 40, 40);
    [_editBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [_editBtn setTitleColor:TEXT_COLOR_1 forState:UIControlStateNormal];
    [_editBtn addTarget:self action:@selector(changeNavBar) forControlEvents:UIControlEventTouchUpInside];
    _editBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_editBtn];
    
    _deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _deleteBtn.frame = CGRectMake(0, 0, 40, 40);
    [_deleteBtn setTitleColor:TEXT_COLOR_1 forState:UIControlStateNormal];
    [_deleteBtn setTitle:@"取消" forState:UIControlStateNormal];
    [_deleteBtn addTarget:self action:@selector(changeNavBar) forControlEvents:UIControlEventTouchUpInside];
    _deleteBtn.titleLabel.font = [UIFont systemFontOfSize:14];
}

- (void)changeNavBar
{
    
    _canDelete = !_canDelete;
    /*
        1.更改右上角按钮的文字
        2.隐藏总价 改变最后一行的格式
        3.取消按钮置灰
     */
    if(_canDelete == YES)
    {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_deleteBtn];
    }else
    {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_editBtn];
    }

    [_tableView reloadData];
}

- (void)maketableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - TABBAR_HEIGHT) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = BACKGROUND_COLOR;
    [self.view addSubview:_tableView];
}

#pragma mark -- tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  _canDelete == YES ? _deleteDataArray.count + 1 : _accountDataArray.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if(indexPath.row == _requestArray.count)
    {
        static NSString *cellID = @"allChooseCell";
        
        LGChooseAllTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellID];
        
        if(cell == nil)
        {
            cell = [[NSBundle mainBundle] loadNibNamed:@"LGChooseAllTableViewCell" owner:self options:nil][0];
        }
        
        if(_canDelete == YES)
        {
            cell.chooseAll = _deleteArray.count == _deleteDataArray.count ? YES : NO;
        }else
        {
            cell.chooseAll = _totalPrice == _productAllPrice ? YES : NO;
        }
        
        cell.delegate = self;
        
        [cell setPrice:_totalPrice AndStrleWithDeleteType:_canDelete deleteArray:_deleteArray];
        
        return cell;
        
    }else
    {
        static NSString *cellIdentifier =  @"LGShopTableViewCell";
        
        LGShopTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        
        if(cell == nil)
        {
            cell = [[NSBundle mainBundle] loadNibNamed:@"LGShopTableViewCell" owner:self options:nil][0];
        }
        
        if(_canDelete == YES)
        {
            [cell setShopCellWithModel:_deleteDataArray[indexPath.row]];
        }else
        {
            [cell setShopCellWithModel:_accountDataArray[indexPath.row]];
        }
        
        
        
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == _requestArray.count)
    {
        
    }else
    {
        /*
         如果是可以删除点击的时候 创建一个数组 记录删除的数据
         如果是结算 就记录总价
        */
        
        LGShopModel *model = [[LGShopModel alloc] init];
        if(_canDelete == YES)
        {
            model = _deleteDataArray[indexPath.row];
            model.chooseOrNot = !model.chooseOrNot;
            if(model.chooseOrNot == YES)
            {
                [_deleteArray addObject:model];
            }else
            {
                [_deleteArray removeObject:model];
            }

        }else
        {
            model = _deleteDataArray[indexPath.row];
            model.chooseOrNot = !model.chooseOrNot;
            if(model.chooseOrNot == YES)
            {
                _totalPrice += model.price;
            }else
            {
                _totalPrice -= model.price;
            }
        }
        
        [tableView reloadData];
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return indexPath.row == _requestArray.count ? 50 : 120;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1f;
}


#pragma mark -- 全选点击
- (void)ChooseAllCommodityWithStatus:(BOOL)allChooseStatus
{
    if(_canDelete == YES)
    {
        /*
            1. 遍历删除数组数据源，把没选择的全部选择上
            2.将没选择的添加进删除数组
         */
        for (LGShopModel *model in _deleteDataArray) {
            
            if(allChooseStatus == YES)//全选删除
            {
                if(model.chooseOrNot == NO)
                {
                    model.chooseOrNot = YES;
                    [_deleteArray addObject:model];
                }
            }else//反全选
            {
                model.chooseOrNot = NO;
                [_deleteArray removeObject:model];
            }
        }
        
    }else
    {
        for (LGShopModel *model in _deleteDataArray) {
            
            if(allChooseStatus == YES)
            {
                if(model.chooseOrNot == NO)
                {
                    model.chooseOrNot = YES;
                    _totalPrice += model.price;
                }

            }else
            {
                model.chooseOrNot = NO;
                _totalPrice -= model.price;
            }
        }
    }
    
    [_tableView reloadData];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
